﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Shared
{
    public class Configuration
    {
        #region Fields

        /// <summary>
        /// Dictionary which contains the configuration data.
        /// </summary>
        private Dictionary<string, string> Data = new Dictionary<string, string>();

        #endregion

        #region Constructor

        /// <summary>
        /// Constructs a new configuration object.
        /// </summary>
        /// <param name="ConfigFile">The configuration file.</param>
        public Configuration(string ConfigFile)
        {
            if (File.Exists(ConfigFile))
            {
                this.Load(ConfigFile);
            }
            else
            {
                throw new Exception("Could not find configuration file.");
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Loads the data from the configuration files.
        /// </summary>
        /// <param name="File">The configuration file.</param>
        private void Load(string File)
        {
            StreamReader Reader = new StreamReader(File);

            while (!Reader.EndOfStream)
            {
                string Line = Reader.ReadLine();

                if (Line.StartsWith(";") || Line.StartsWith("#"))
                {
                    continue;
                }

                string[] Pair = Line.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);

                if (Pair.Length != 2)
                {
                    continue;
                }

                this.Data.Add(Pair[0], Pair[1]);
            }
        }

        /// <summary>
        /// Gets a value from the configuration.
        /// </summary>
        /// <param name="Key">Configuration key variable.</param>
        /// <param name="Default">Default value.</param>
        /// <returns></returns>
        public string Get(string Key, string Default)
        {
            try
            {
                return this.Data[Key];
            }
            catch
            {
                return Default;
            }
        }

        #endregion
    }
}
